const { Service } = require('egg');
const { tableToList } = require('../utils/tools');


module.exports = class emptyroomService extends Service {
  /**
   * 爬取空闲教室
   * @param {string} term 学期
   * @param {string} zc *
   * @param {string} xq *
   * @param {string} jxl *
   * @return {Array} *
   */
  async table(term, zc, xq, jxl) {
    const Cookie = this.ctx.state.Cookie;
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbxx/kxjs_Querydata`;
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        typewhere: 'jszq',
        xnxqh: term,
        zc,
        zc2: zc,
        xq,
        xq2: xq,
        jxqbh: '',
        jxlbh: jxl,
        jsbh: '',
        bjfh: '=',
        rnrs: '',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    });
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList');
        return tableList;
      } catch (err) {
        throw err;
      }
    }
    return {};
  }
};
